//
//  KBComposeController.swift
//  KimboWeiBoSwift
//
//  Created by kimbo on 15/12/27.
//  Copyright © 2015年 kimbo. All rights reserved.
//

import UIKit
import SVProgressHUD

class KBComposeController: UIViewController {

    // MARK: - 属性
    private var toolBarBottomConstraint: NSLayoutConstraint?
    
    // 发微博最大字数
    private let maxTipLength = 25
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //重要，否则modal出来的时候可以看到后面控制器的内容
        view.backgroundColor = UIColor.whiteColor()
        
        // 设置导航栏
        setupNav()
        // 设置textView
        // 作用:当控制器是导航控制器的子控制器时,（UIScrollView或子类）会自动往下滚动64
        // UIScrollView或子类必须是控制器的view,或者 UIScrollView或子类 是控制器的第一个子view
        setupTextView()
        // 设置toolBar
        setupToolBar()
        // 设置剩余字数提示
        setupTipLengthLabel()
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        //view显示后弹出键盘
        textView.becomeFirstResponder()
    }
    
    // 设置剩余字数提示
    private func setupTipLengthLabel() {
        view.addSubview(tipLengthLabel)
        
        tipLengthLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -4, y: -4))
        // 设置最大发微博字数
        tipLengthLabel.text = String(maxTipLength)
    }
    
    // 设置导航栏
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancleItemDidClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendItemDidClick")
        
        navigationItem.rightBarButtonItem?.enabled = false //默认不能发送
        
        setupTitleView() //设置导航栏标题
    }
    
    //设置导航栏标题(可以看到此控制器证明已经登录过)
    private func setupTitleView() {
        let prefix = "转发微博"
        
        if let userName = KBUserAccount.loadUserAccount()?.screen_name {
            let text = prefix + "\n" + userName
            //设置属性文本
            let attributeString = NSMutableAttributedString(string: text)
            //用户名在整个文本中的范围
            let range = (text as NSString).rangeOfString(userName)
            
            attributeString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(11), range: range)
            
            attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.grayColor(), range: range)
            //导航栏标题文本
            titleLabel.attributedText = attributeString
            titleLabel.sizeToFit()
            
            navigationItem.titleView = titleLabel
            
        } else { //没有获取到用户名
            navigationItem.title = prefix
        }
    }
    
    // 设置textView
    private func setupTextView() {
        view.addSubview(textView)

        // 管理游离控制器
        addChildViewController(emoticonsController)
        
        textView.delegate = self
        
        //添加约束
        textView.ff_Fill(view)
        
    }
    
    // 发出键盘弹出通知回调方法
    func keyboardWillChangeFrame(notification: NSNotification) {
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        // 获取键盘弹出最终的frame
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        // 注意：在键盘弹出过程中，height没有改变，所以不能直接赋值为键盘的高度
        toolBarBottomConstraint?.constant = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    // 设置toolBar
    private func setupToolBar() {
        view.addSubview(toolBar)
        // 添加约束
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        
        toolBarBottomConstraint = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 设置item
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            let imageName = dict["imageName"]! //图片
            let action = dict["action"]! // 事件
            
            //创建item
            let item = UIBarButtonItem(imageName: imageName)
            
            //给item里面的按钮添加事件
            //注意：如果方法是字符串可以直接写，但要是变量或常量就要加Selector
            let btn = item.customView as! UIButton
            btn.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            
            items.append(item)
            
            //创建弹簧item
            let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            
            items.append(flexibleSpace)
        }
        // 移除最后一根弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    
    //点击取消
    @objc private func cancleItemDidClick() {
        SVProgressHUD.dismiss()
        
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //点击发送微博
    @objc private func sendItemDidClick() {
        let status = textView.emoticonText()
        
        if maxTipLength - status.characters.count < 0 {
            SVProgressHUD.showErrorWithStatus("微博内容超出长度")
            return
        }
        
        // 来到这里，提示用户
        SVProgressHUD.showWithStatus("正在发送中")
        
        KBNetWorkTool.sharedInstance.sendStatus(status) { (result, error) -> () in
            if error != nil || result == nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力,请稍后尝试")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("微博发送成功")
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.cancleItemDidClick()
            })
        }
    }
    
    // MARK: - 点击toolBar方法
    //点击图片
    @objc private func picture() {
        print("picture")
    }
    
    //点击mention
    @objc private func mention() {
        print("mention")
    }
    
    //点击trend
    @objc private func trend() {
        print("trend")
    }
    
    //点击emoticon
    @objc private func emoticon() {

        textView.resignFirstResponder()
        // 延迟，解决键盘跳动问题(时间相隔太短)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            //如果是系统键盘就弹出表情键盘，否则弹出系统键盘
            self.textView.inputView = self.textView.inputView == nil ? self.emoticonsController.view : nil
            
            self.textView.becomeFirstResponder()
        }
    }
    
    //点击add
    @objc private func add() {
        print("add")
    }
    
    // MARK: - 懒加载
    /* 导航栏标题文本 */
    private lazy var titleLabel: UILabel = {
       let titleLabel = UILabel()
        
        titleLabel.textAlignment = NSTextAlignment.Center
        
        titleLabel.numberOfLines = 0
        
        titleLabel.font = UIFont.systemFontOfSize(14)
        
        return titleLabel
    }()

    /* toolBar */
    private lazy var toolBar: UIToolbar = {
       let toolBar = UIToolbar()
        
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        return toolBar
    }()
    
    /* 输入文本框 */
    private lazy var textView: KBPlaceholdTextView = {
        let textView = KBPlaceholdTextView()
        
        textView.backgroundColor = UIColor.brownColor()
        
        textView.font = UIFont.systemFontOfSize(18)
        
        textView.placeholdText = "分享新鲜事..."
        
        textView.alwaysBounceVertical = true //输入文本框可以垂直拖拽
        
        // 设置当拖拽时消失keyboard
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return textView
    }()
    
    /* 表情键盘 */
    private lazy var emoticonsController: KBEmoticonsController = KBEmoticonsController(textView: self.textView)
    
    /* 剩余字数提示 */
    private lazy var tipLengthLabel: UILabel = {
       let tipLengthLabel = UILabel()
        
        tipLengthLabel.textColor = UIColor.lightGrayColor()
        
        tipLengthLabel.font = UIFont.systemFontOfSize(14)
        
        return tipLengthLabel
    }()
}


// MARK: - 扩展KBComposeController 遵守UITextViewDelegate协议
extension KBComposeController: UITextViewDelegate {
    // 输入文本发生改变时调用
    func textViewDidChange(textView: UITextView) {
        //当有输入文本时可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 获取textview的现有字数
        let count = textView.emoticonText().characters.count
        
        let length = maxTipLength - count
        
        // 显示剩余字数
        tipLengthLabel.text = String(length)
        
        tipLengthLabel.textColor = length > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
    }
}

